<template>
  <div class="upload-file">
    <el-upload
      class="upload-demo"
      action
      :http-request="HandleUploadSelf"
      :before-upload="handleBeforeUpload"
      :on-error="handleUploadError"
      :on-exceed="handleExceed"
      :on-preview="handlePreview"
      :headers="headers"
      :on-remove="handleDelete"
      multiple
      :limit="limit"
      :file-list="fileList"
    >
      <!-- 上传按钮 -->
      <el-button size="mini" type="primary">选取附件</el-button>
      <!-- 上传提示 -->
      <div class="el-upload__tip" slot="tip" v-if="showTip">
        请上传
        <template v-if="fileSize">
          大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
        </template>
        <template v-if="fileType">
          格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b>
        </template>
        的文件
        <div style="color: #f56c6c">点击文件名即可下载文件</div>
      </div>
    </el-upload>
    <el-progress v-if="progressFlag" :percentage="loadProgress"></el-progress>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { delFile } from "@/api/login";
import axios from "axios";
import { downloadFile } from "@/api/smartParks/environment/opmEnvRule";

export default {
  props: {
    // 值
    value: [String, Object, Array],
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 20,
    },
    fileListTem: {
      type: Array,
      default:()=>{},
    },
    limit: {
      type: Number,
      default: 5,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["pdf", "xls", "xlsx", "docx", "png", "jpg", "jpeg"],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/system/file/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileList: [],
      loadProgress: 0, // 动态显示进度条
      progressFlag: false, // 关闭进度条
    };
  },
  watch: {
    fileListTem(val) {
      this.fileList = val;
    },
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
  },

  methods: {
    // 封面自定义上传图片
    HandleUploadSelf(file, fileList) {
      axios({
        method: "post",
        url: this.uploadFileUrl,
        data: this.formData({ file: file.file }),
        headers: {
          "Content-Type": "multipart/form-data",
          Authorization: "Bearer " + getToken(),
        },
        //上传进度
        onUploadProgress: (progressEvent) => {
          this.progressFlag = true;
          this.loadProgress =
            ((progressEvent.loaded / progressEvent.total) * 100) | 0;
          if (this.loadProgress >= 99) {
            this.loadProgress = 99;
          }
        },
      })
        .then((resf) => {
          let res = resf.data;
          if (res.code === 200) {
            this.progressFlag = false;
            this.loadProgress = 100;
            let tmepObj = {};
            tmepObj.name = res.data.name;
            tmepObj.id = res.data.id;
            tmepObj.url = "http://" + res.data.url;
            this.fileList.push(tmepObj);
            this.$message.success("上传成功");
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },

    handlePreview(file) {
      let index = file.name.indexOf(".");
      let name = file.name.slice(0, index);
      downloadFile(file.url, name);
    },
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件类型
      if (this.fileType) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        const isTypeOk = this.fileType.some((type) => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
        if (!isTypeOk) {
          this.$message.error(
            `文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`
          );
          return false;
        }
      }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      return true;
    },
    // 文件个数超出
    handleExceed() {
      this.$message.error(`只允许上传单个文件`);
    },
    // 上传失败
    handleUploadError(err) {
      this.$message.error("上传失败, 请重试");
    },

    // 删除文件
    handleDelete(file, fileList) {
      if (file && file.status === "success") {
        //在执行删除
        let { url } = file;
        const i = this.fileList.findIndex((item) => item.url === url);
        this.fileList.splice(i, 1);
        delFile(file.id).then((res) => {
          this.$message.success("删除成功");
        });
      }
    },
  },
  created() {
    this.fileList = this.fileListTem;
  },
};
</script>

<style scoped lang="scss">
.upload-file-uploader {
  margin-bottom: 5px;
}
.upload-file-list .el-upload-list__item {
  border: 1px solid #e4e7ed;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
}
.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}
.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}
</style>
